package com.sendi.system.dao;

import java.io.Serializable;
 
import java.sql.SQLException;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
 
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.dao.DataAccessException;
 
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
 

public class CommonDaoHibernate extends HibernateDaoSupport {
	public boolean exists(Class entityClass, Serializable id)
	{
	    Object entity = getHibernateTemplate().get(entityClass, id);
	    return (entity == null);
	}
	public Object get(Class entityClass, Serializable id){
		return getHibernateTemplate().get(entityClass, id);
	}
	public boolean contains(Object obj) throws DataAccessException {
		return getHibernateTemplate().contains(obj);
	}
  
	public void save(Object obj){
		getHibernateTemplate().saveOrUpdate(obj);
	}
	public void saveOrUpdate(Object obj) throws DataAccessException {
		this.getHibernateTemplate().saveOrUpdate(obj);
	}
	public void update(Object obj){
		getHibernateTemplate().update(obj);
	}
	public void delete(Object obj){
		getHibernateTemplate().delete(obj);
	}
	protected static String removeSelect(String hql)
	{
	    int beginPos = hql.toLowerCase().indexOf("from");
	    return hql.substring(beginPos);
	}

	protected static String removeOrders(String hql)
	{
	    Pattern p = Pattern.compile("order\\s*by[\\w|\\W|\\s|\\S]*", 2);
	    Matcher m = p.matcher(hql);
	    StringBuffer sb = new StringBuffer();
	    while (m.find()) {
	      m.appendReplacement(sb, "");
	    }
	    m.appendTail(sb);
	    return sb.toString();
	}
	public long getCount(String hql, Object[] values)
	{
	    String countQueryString = " select count (*) " + removeSelect(removeOrders(hql));
	    List countlist = getHibernateTemplate().find(countQueryString, values);
	    long totalCount = ((Long)countlist.get(0)).longValue();
	    return totalCount;
	}
	public List findByHql(String hql,Object[] values){
		return getHibernateTemplate().find(hql, values);
	}
	public List findDatasByHqlWithPage(final String hql, final int start,final int limit){
		List list = getHibernateTemplate().executeFind(new HibernateCallback() {
		    public Object doInHibernate(Session session)
		      throws HibernateException, SQLException {
			     Query query = session.createQuery(hql).setFirstResult(start).setMaxResults(limit);
			     return query.list();
		    }
		});
		return list;
	}
 
	public List findByHQL(String hql){
		return getHibernateTemplate().find(hql);
	}
}
